//
//  LikeOfCell.m
//  PetAPP
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "LikeOfCell.h"
#import "NetworkingHandle.h"
#import "ModelOfContent.h"
#import "TwoPicsOfCell.h"
#import "ThirdPicsOfCell.h"
#import "SixPicsOfCell.h"
#import "OnePicsOfCell.h"
#import "FourPicsOfCell.h"
#import "NinePicsOfCell.h"
#import <MJRefresh.h>
#import <DKNightVersion.h>
#import "LikeOfCustom.h"
#import "LikeOfCustomForNone.h"
#import "ZeroPicsOfCell.h"


@interface LikeOfCell () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UICollectionView *collection;

@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, retain) NSMutableArray *dataArr;

@property (nonatomic, assign) NSInteger refreshNum;

@property (nonatomic, retain) UIButton *buttonOfTop;

@property (nonatomic, assign) BOOL footerflag;

@property (nonatomic, retain) LikeOfCustom *viewOfLogin;

@property (nonatomic, retain) LikeOfCustomForNone *viewOfNone;

@end

@implementation LikeOfCell

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"handleData"];
    [[NSNotificationCenter defaultCenter] removeObserver:@"loginState"];
    [_viewOfLogin release];
    [_buttonOfTop release];
    [_dataArr release];
    [_collection release];
    [_flowLayout release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        [self createCollectionViewWithFrame:(CGRect){.size = frame.size}];
        
        [self handleData];
        [self handleRefresh];
        [[NSNotificationCenter defaultCenter] addObserverForName:@"handleData" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            [self handleData];
        }];
        [[NSNotificationCenter defaultCenter] addObserverForName:@"loginState" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            [self handleData];
        }];
        
    }
    return self;
}

- (void)handleHidden {

    if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"loginState"] boolValue]) {
        self.viewOfLogin.hidden = YES;
        if (0 == self.dataArr.count) {
            self.collection.hidden = YES;
            self.viewOfNone.hidden = NO;
        }else {
            self.collection.hidden = NO;
            self.viewOfNone.hidden = YES;
        }
    }else {
        self.viewOfLogin.hidden = NO;
        self.collection.hidden = YES;
        self.viewOfNone.hidden = YES;
    }

}

- (void)handleRefresh {
    
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.refreshNum = 1;
        [self handleData];
    }];
    
}

/** 加载数据 */
- (void)handleData {
                        
    NSString *url = @"http://bbs.chinapet.com/plugin.php?id=leepet_thread:api&action=threadListNew";
    NSString *body = [NSString stringWithFormat: @"condition=follow&page=1&pagesize=%ld0&service=threadListNew&sign=4ee82af2f57d3329f27891de1e2dcfe5&version=d1bd83a33f1a841ab7fda32449746cc4", self.refreshNum];
    NSString *cookie = [NSString stringWithFormat:@"leepetphone%%5Bpassword%%5D=%@; leepetphone[source]=ios; leepetphone[uid]=%@; leepetphone[username]=%@", [[NSUserDefaults standardUserDefaults] stringForKey:@"password"], [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"], [[[NSUserDefaults standardUserDefaults] stringForKey:@"username"] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    if (![[[NSUserDefaults standardUserDefaults] stringForKey:@"loginState"] boolValue]) {
        cookie = @"";
    }
    NSDictionary *dic = @{@"Content-Type" : @"application/x-www-form-urlencoded", @"Cookie" : cookie};
    
    [NetworkingHandle handleWorkData:url AndBody:body value:dic handleBlock:^(id result) {
        NSArray *tempArr = [result objectForKey:@"array"];
        self.dataArr = [NSMutableArray array];
        
        for (NSDictionary *dic in tempArr) {
            ModelOfContent *model = [[ModelOfContent alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:model];
            [model release];
        }
        
        if (_footerflag == NO) {
            self.collection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                self.refreshNum++;
                [self handleData];
            }];
        }
        _footerflag = YES;
        [self.collection.mj_header endRefreshing];
        [self.collection.mj_footer endRefreshing];
        [self.collection reloadData];
        
    }];
    [self handleHidden];
    
    
}
/** 创建CollectionView */
- (void)createCollectionViewWithFrame:(CGRect)frame {
    self.refreshNum = 1;
    
    CGFloat width = self.frame.size.width;
    self.flowLayout = [UICollectionViewFlowLayout new];
    self.flowLayout.itemSize = CGSizeMake(width, 300);
    
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.flowLayout.minimumLineSpacing = 10;
    
    
    self.collection = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:self.flowLayout];
    [self addSubview:self.collection];
    [_collection release];
    
    self.collection.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0], [UIColor whiteColor]);
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.showsVerticalScrollIndicator = NO;
    
    self.collection.scrollsToTop = YES;
    
    self.viewOfLogin = [[LikeOfCustom alloc] initWithFrame:CGRectMake(0, self.contentView.frame.size.height / 4, self.contentView.frame.size.width, self.contentView.frame.size.height / 4 * 2)];
    [self.contentView addSubview:_viewOfLogin];
    [_viewOfLogin release];
    
    self.viewOfNone = [[LikeOfCustomForNone alloc] initWithFrame:CGRectMake(0, self.contentView.frame.size.height / 4, self.contentView.frame.size.width, self.contentView.frame.size.height / 4 * 2)];
    [self.contentView addSubview:_viewOfNone];
    [_viewOfNone release];
    
    
    self.viewOfLogin.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.2952 green:0.2952 blue:0.2952 alpha:1.0]);
    
    
    
    [self.collection registerClass:[OnePicsOfCell class] forCellWithReuseIdentifier:@"poolOfOne"];
    [self.collection registerClass:[TwoPicsOfCell class] forCellWithReuseIdentifier:@"poolOfTwo"];
    [self.collection registerClass:[ThirdPicsOfCell class] forCellWithReuseIdentifier:@"poolOfThird"];
    [self.collection registerClass:[FourPicsOfCell class] forCellWithReuseIdentifier:@"poolOfFour"];
    [self.collection registerClass:[SixPicsOfCell class] forCellWithReuseIdentifier:@"poolOfSix"];
    [self.collection registerClass:[NinePicsOfCell class] forCellWithReuseIdentifier:@"poolOfNine"];
    [self.collection registerClass:[ZeroPicsOfCell class] forCellWithReuseIdentifier:@"poolOfZero"];


    self.buttonOfTop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOfTop.frame = CGRectMake(self.frame.size.width - 55, self.frame.size.height - 50, 40, 40);
    [self addSubview:self.buttonOfTop];
    [self.buttonOfTop setImage:[UIImage imageNamed:@"top"] forState:UIControlStateNormal];
    
    UIBezierPath *backgroundPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 3, 40, 40) cornerRadius:20];
    
    self.buttonOfTop.layer.shadowPath = backgroundPath.CGPath;
    self.buttonOfTop.layer.shadowOpacity = 0.9;
    self.buttonOfTop.layer.shadowRadius = 0;
    self.buttonOfTop.layer.dk_shadowColorPicker = DKColorWithColors([UIColor colorWithRed:1.0 green:0.8964 blue:0.2489 alpha:1.0], [UIColor whiteColor]);
    [self.buttonOfTop addTarget:self action:@selector(backTopWithButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.buttonOfTop.hidden = YES;
#pragma mark - 创建观察者
    
    /** 核心:观察者 观察 某一个对象的属性变化, */
    //VC观察collection的contentOffset属性
    [self.collection addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"context"];
    
}

/** 当被观察者属性发生变化的时候,调用此方法. */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    
    CGFloat y = [[change objectForKey:@"new"] CGPointValue].y;
    if (y > 1000) {
        self.buttonOfTop.hidden = NO;
    }else {
        self.buttonOfTop.hidden = YES;
    }
    
}


- (void)backTopWithButton:(UIButton *)button {
    // 当点击 button 回到顶部
    [self.collection scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    
    
}


/** 设置cell行数 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArr.count;
}
#pragma mark - 设置cell的样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ModelOfContent *model = self.dataArr[indexPath.item];
    
    if (model.pics.count == 0) {
        ZeroPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfZero" forIndexPath:indexPath];
        [cell passContentWithModel:model];
        
        
        return cell;
        
    }else if (model.pics.count == 1){
        OnePicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfOne" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
    }else if (model.pics.count == 2) {
        TwoPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfTwo" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else if (model.pics.count == 3) {
        ThirdPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfThird" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else if (model.pics.count >= 4 && model.pics.count <= 5){
        FourPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfFour" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
        
        
    }else if (model.pics.count >= 6 && model.pics.count <= 8) {
        SixPicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfSix" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    } else {
        NinePicsOfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolOfNine" forIndexPath:indexPath];
        
        [cell passContentWithModel:model];
        
        return cell;
        
    }
    
    
    
}


#pragma mark - 返回每一行高度的方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelOfContent *model = [self.dataArr objectAtIndex:indexPath.item];
    
    
    return CGSizeMake(self.frame.size.width, [CellOfContent returnCGSizeForModel:model]);
    
}

#pragma mark - 通过消息中心推出详情页面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelOfContent *model = [self.dataArr objectAtIndex:indexPath.item];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PushVC" object:@"1" userInfo:@{@"tid":model.tid}];

}




/** collectionCell 的子控件的布局通常在此方法中设置 */
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    
    //    NSLog(@"%@",layoutAttributes);
    self.contentView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.2952 green:0.2952 blue:0.2952 alpha:1.0]);
    
}



@end
